<?php
namespace app\front\service\v2;
use app\front\service\GetMsgService;
//use app\front\service\v2\Redis;
class AliCallBack extends GetMsgService
{
    
    private static $_instance;
    
    //private 构造函数
    private function __construct() {
        // echo " I'm construct! process id is " . getmypid() . " and thread id is " . Thread::getCurrentThreadId() . "\n";
    }
    
    private function __clone() {
        //    echo " I'm clone! process id is " . getmypid() . " and thread id is " . Thread::getCurrentThreadId() . "\n";
    }
    
    //单例方法访问类实例
    public static function getInstance() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    /**
     * 1.获取数据
     * 2.验证签名
     * 3.验证是否来自支付宝的请求
     * 4.验证交易状态
     * 5.验证订单号和金额
     * 6.更改订单状态
     */
    public function AliNotify(){
        
        // 1.获取数据
        $postData=input('param.');
        
        logs('log.txt', $postData);
        if($postData['sign_type']=='MD5'){
            //2.验证签名
            if(!checkSign($postData,2,'MD5')){
                logs('log.txt', 'MD5签名失败!');
                exit();
            }else{
                logs('log.txt', 'MD5签名成功!');
            }
        }else if($postData['sign_type']=='RSA'){
            //2.验证签名
            if(!rsaCheck(getSign($postData,$source=2,$type = 'RSA',$getStr=true),config('APPPUBLICEKEY'), $postData['sign'])){
                logs('log.txt', 'RSA签名失败!');
                exit();
            }else{
                logs('log.txt', 'RSA签名成功!');
            }
        }else if($postData['sign_type']=='RSA2'){
            //2.验证签名
            if(!rsaCheck(getSign($postData,$source=2,$type = 'RSA2',$getStr=true,$checkRSA2=true),config('NEW_APPPUBLICEKEY'), $postData['sign'],'RSA2')){
                logs('log.txt', 'RSA2签名失败!');
                exit();
            }else{
                logs('log.txt', 'RSA2签名成功!');
            }
        }else{
            logs('log.txt', '签名有误!');
            exit();
        }
        
        //3.验证是否来自支付宝的请求
        if(!isAlipay($postData)){
            logs('log.txt', '不是来自支付宝的通知!');
            exit();
        }else{
            logs('log.txt', '是来自支付宝的通知验证通过!');
        }
        // 4.验证交易状态
        if(!checkAliOrderStatus($postData)){
            logs('log.txt', '交易未完成!');
            exit();
        }else{
            logs('log.txt', '交易成功!');
        }
        //5. 验证订单号和金额
        //获取支付发送过来的订单号  在商户订单表中查询对应的金额 然后和支付宝发送过来的做对比
        if($postData['sign_type']=='RSA2'){
            logs('log.txt', '订单号:' . $postData['out_trade_no'] . '订单金额:' . $postData['total_amount']);
        }else{
            logs('log.txt', '订单号:' . $postData['out_trade_no'] . '订单金额:' . $postData['total_fee']);
        }
        
        
        //更改订单状态
        //通知支付宝
        echo 'success';
    }
  
}

